/**
 *
 */
package de.guidoludwig.jtm;

import java.awt.Image;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import de.guidoludwig.af.ApplicationFrame;
import de.guidoludwig.af.Splash;
import de.guidoludwig.af.SwingUtil;
import de.guidoludwig.jtm.client.artists.ArtistApplication;
import de.guidoludwig.jtm.client.shows.ShowApplication;
import de.guidoludwig.jtm.server.ArchiveRepository;
import de.guidoludwig.jtm.server.ArtistRepository;
import de.guidoludwig.jtm.server.Server;
import de.guidoludwig.jtm.server.ShowRepository;
import de.guidoludwig.jtm.util.LogHandler;



/**
 * @author guido
 *
 */
public class JTM {

	private static boolean indexLucene = false;

    private static final JTM INSTANCE = new JTM();

    private LogHandler handler;

    private JTM() {
    	// NO
    }

    private void init() throws ClassNotFoundException, SQLException, IOException {
    	Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).setLevel(Level.FINEST);
    	handler = new de.guidoludwig.jtm.util.LogHandler();
    	Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).addHandler(handler);

    	ImageIcon icon = SwingUtil.loadIcon("splash.jpg");
    	Image image = icon == null ? null : icon.getImage();
    	Splash splash = new Splash(image, "JTradelistmanager 0.7alpha");
        splash.open();

        splash.setMessage("Migrating DB");
        Migrator.getInstance().migrate("data/jtm.db");

        splash.setMessage("Initializing Server");
        Server.getInstance();


        if (indexLucene) {
            splash.setMessage("Indexing Lucene");
            indexLucene();
		}

        splash.setMessage("Preparing UI");

		ApplicationFrame.INSTANCE.register(ArtistApplication.INSTANCE);
		ApplicationFrame.INSTANCE.register(ShowApplication.INSTANCE);

		ApplicationFrame.INSTANCE.start();
        splash.close();




    }

    private static void indexLucene() {
        try {
        	ArtistRepository repo = new ArtistRepository();
        	repo.reindex();
        	ShowRepository reps = new ShowRepository();
        	reps.reindex();
        	ArchiveRepository repa = new ArchiveRepository();
        	repa.reindex();
			Server.getInstance().reindexLucene();
		} catch (InterruptedException e) {
			e.printStackTrace();
			System.exit(0);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    }

	public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
        try {
            SwingUtil.chooseLookAndFeel();
    		INSTANCE.init();
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, e.getMessage());
        }

	}

}
